/**
 * 注册
 * page注册
 */
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:openinstall_flutter_plugin/openinstall_flutter_plugin.dart';
import 'package:qgchat/common/action/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/widgets/tipsDialog.dart';

class Register extends StatefulWidget {
  Register({Key key}) : super(key: key);

  @override
  RregisterState createState() => RregisterState();
}

class RregisterState extends State<Register> {
  // 获取验证码文字
  String _getCodeText = "获取验证码";
  // 验证码倒计时时间
  int _codeDate = 59;
  // 倒计时控制器
  Timer _codeTimer;
  // 设备识别码
  String _phoneId;
  // 上级token
  String invationToken;

  // ipt手机号码输入控制器
  TextEditingController iptPhoneController;
  // ipt验证码控制器
  TextEditingController iptPINController;
  // ipt登录密码控制器
  TextEditingController iptPWController;
  // ipt重复密码控制器
  TextEditingController iptRePWController;

  OpeninstallFlutterPlugin _openinstallFlutterPlugin =
      OpeninstallFlutterPlugin();

  RregisterState() {
    _openinstallFlutterPlugin.init(wakeupHandler); // 拉起
    _openinstallFlutterPlugin.install(installHandler); // 安装
  }

// life-------------------------------------------------------------------------

  @override
  void initState() {
    iptPhoneController = TextEditingController();
    iptPINController = TextEditingController();
    iptPWController = TextEditingController();
    iptRePWController = TextEditingController();
    _getPhoneInfo();
    super.initState();
  }

  @override
  void dispose() {
    _codeTimer?.cancel();
    _codeTimer = null;
    iptPhoneController.dispose();
    iptPINController.dispose();
    iptPWController.dispose();
    iptRePWController.dispose();
    super.dispose();
  }

// methods-----------------------------------------------------------------------

  // back
  void _back() {
    Navigator.of(context).pop();
  }

  // 获取验证码
  _getCodeAction() async {
    if (_codeTimer != null) {
      // 冷却中
      return null;
    }
    String phone = iptPhoneController.text;
    var result = await UserApis.getPIN(phone, context);
    if (result != null && result['status'] == 1) {
      debugPrint(result.toString());
      showToast('验证码已发送,请注意查收');
      _codeTimer = Timer.periodic(Duration(seconds: 1), (timer) {
        setState(() {
          if (_codeDate > 0) {
            _getCodeText = '${_codeDate--}秒重新获取';
          } else {
            _getCodeText = '获取验证码';
            _codeDate = 59;
            _codeTimer.cancel();
            _codeTimer = null;
          }
        });
      });
    }
  }

  // 注册
  void _register() async {
    String phone = iptPhoneController.text;
    String PIN = iptPINController.text;
    var result = await UserApis.register(phone, PIN, _phoneId, invationToken);
    if (result != null && result['status'] == 1) {
      _openinstallFlutterPlugin.reportRegister(); // 注册统计
      await CommonAction.initAppData(context, result['msg']);
      showToast("登录成功");
      goPage(context, "/", replace: true);
    }
  }

  // 获取设备信息
  void _getPhoneInfo() async {
    DeviceInfoPlugin phoneInfo = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await phoneInfo.androidInfo;
      _phoneId = androidInfo.androidId;
      print('phoneId === $_phoneId');
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await phoneInfo.iosInfo;
      _phoneId = iosInfo.identifierForVendor;
    }
  }

  Future wakeupHandler(Map<String, dynamic> data) async {
    print('''
      wakeup result:
        channel = ${data['channelCode']}
        data = ${data['bindData']}
    ''');
    if (data['bindData'] != null) {
      Map map = json.decode(data['bindData']);
      if (map.containsKey('invation_token')) {
        invationToken = map['invation_token'];
      }
    }
  }

  Future installHandler(Map<String, dynamic> data) async {
    // TipsDialog.test(context, ["$data"]);
    if (data['bindData'] != null) {
      Map map = json.decode(data['bindData']);
      if (map.containsKey('invation_token')) {
        invationToken = map['invation_token'];
      }
    }
  }

// widget-----------------------------------------------------------------------

  /// 背景图
  Widget BG() {
    return Container(
      width: w100(context),
      height: h100(context),
      child: Image.asset(
        'assets/images/homeBg1.png',
        fit: BoxFit.cover,
      ),
    );
  }

  /// 返回
  Widget back() {
    return Container(
      margin: EdgeInsets.only(
        top: px(35),
        left: px(35),
      ),
      child: GestureDetector(
        onTap: _back,
        child: Container(
          alignment: Alignment.topLeft,
          margin: EdgeInsets.all(px(10)),
          child: Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
            size: px(36),
          ),
        ),
      ),
    );
  }

  // 数字输入框构造器
  Widget _inputNumberBuilder(
      String labelText, TextEditingController controller) {
    return Container(
      margin: EdgeInsets.only(top: px(30)),
      child: TextField(
        controller: controller,
        keyboardType: TextInputType.phone,
        inputFormatters: [
          WhitelistingTextInputFormatter.digitsOnly,
          LengthLimitingTextInputFormatter(11),
        ],
        style: TextStyle(color: col("ffffff")),
        decoration: InputDecoration(
          labelText: labelText,
          labelStyle: TextStyle(color: col("d1a3d7")),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: col('d1a3d7')),
          ),
          focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.cyan),
          ),
        ),
      ),
    );
  }

  // 带验证码按钮的输入框
  Widget _inputPINBuilder(String labelText, TextEditingController controller) {
    return Container(
        margin: EdgeInsets.only(top: px(30)),
        child: Stack(
          alignment: AlignmentDirectional.centerEnd,
          children: <Widget>[
            TextField(
              controller: controller,
              keyboardType: TextInputType.phone,
              inputFormatters: [
                WhitelistingTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(8),
              ],
              style: TextStyle(color: col("ffffff")),
              decoration: InputDecoration(
                labelText: labelText,
                labelStyle: TextStyle(color: col("d1a3d7")),
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: col('d1a3d7')),
                ),
                focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.cyan),
                ),
              ),
            ),
            Container(
                height: px(60),
                child: Stack(
                  children: <Widget>[
                    FlatButton(
                      onPressed: _getCodeAction,
                      color: _codeTimer == null
                          ? col('6f53ff')
                          : Colors.transparent,
                      padding: EdgeInsets.symmetric(horizontal: px(30)),
                      shape: RoundedRectangleBorder(
                        side: _codeTimer == null
                            ? BorderSide.none
                            : BorderSide(
                                color: Colors.white,
                                style: BorderStyle.solid,
                                width: px(1),
                              ),
                        borderRadius: BorderRadius.circular(
                          sp(40),
                        ),
                      ),
                      child: Text(
                        _getCodeText,
                        style: TextStyle(
                          color: col("ffffff"),
                          fontSize: px(26),
                          height: 1.2,
                        ),
                      ),
                    ),
                  ],
                )),
          ],
        ));
  }

  // 密码输入框构造函数
  Widget _inputPWBuilder(String labelText, TextEditingController controller) {
    return Container(
      margin: EdgeInsets.only(top: px(30)),
      child: TextField(
        controller: controller,
        obscureText: true,
        style: TextStyle(color: col("ffffff")),
        decoration: InputDecoration(
          labelText: labelText,
          labelStyle: TextStyle(color: col("d1a3d7")),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: col('d1a3d7')),
          ),
          focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.cyan),
          ),
        ),
      ),
    );
  }

  /// 服务协议
  Widget _agreement() {
    return Container(
      margin: EdgeInsets.only(top: px(90)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            "确认登录即代表已阅读并同意",
            style: TextStyle(
              fontSize: px(22),
              color: col("ffffff"),
            ),
          ),
          FlatButton(
            onPressed: () => {},
            padding: EdgeInsets.zero,
            child: Text(
              "《软件服务协议》",
              style: TextStyle(
                fontSize: px(22),
                color: col("ffffff"),
                fontWeight: FontWeight.bold,
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      children: <Widget>[
        BG(),
        Container(
          width: w100(context),
          child: ListView(
            children: <Widget>[
              /// back
              back(),
              Container(
                padding: EdgeInsets.only(
                    bottom: px(50), left: px(60), right: px(60)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: px(90)),
                      child: Text(
                        "注册账号",
                        style: TextStyle(
                          color: col("ffffff"),
                          fontSize: px(50),
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: px(40), bottom: px(50)),
                      child: Text(
                        "欢迎加入我们",
                        style: TextStyle(
                          color: col("eee3fa"),
                          fontSize: px(28),
                        ),
                      ),
                    ),
                    _inputNumberBuilder('手机号码', iptPhoneController),
                    _inputPINBuilder("验证码", iptPINController),
                    // _inputPWBuilder("登录密码", iptPWController),
                    // _inputPWBuilder("重复密码", iptRePWController),
                    Container(
                      width: px(630),
                      height: px(94),
                      margin: EdgeInsets.only(top: px(130)),
                      child: FlatButton(
                        onPressed: _register,
                        color: col("6f53ff"),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(
                            sp(47),
                          ),
                        ),
                        child: Text(
                          "确认",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: px(36),
                          ),
                        ),
                      ),
                    ),
                    // _agreement(),
                  ],
                ),
              )
            ],
          ),
        ),
      ],
    ));
  }
}
